package com.example.duckshop.ui.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.duckshop.MyApplication;
import com.example.duckshop.R;
import com.example.duckshop.adapter.ShopAdapter;
import com.example.duckshop.bean.Shop;
import com.example.duckshop.ui.activity.LoginActivity;
import com.example.duckshop.ui.activity.ShopDetailActivity;
import com.example.duckshop.util.MySqliteOpenHelper;
import com.example.duckshop.util.RecyclerViewSpaces;
import com.example.duckshop.util.SPUtils;
import com.google.android.material.tabs.TabLayout;
import com.youth.banner.Banner;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

/**
 * 首页
 */

public class HomeFragment extends Fragment {
    MySqliteOpenHelper helper = null;
    private Activity myActivity;//上下文
    private TabLayout tabTitle;
    private RecyclerView rvShopList;
    private ShopAdapter mShopAdapter;
    private LinearLayout llEmpty;
    private String[] state = {"0", "1", "2", "3"};
    private String[] title = {"鲁菜", "川菜", "粤菜", "淮扬菜"};
    private String typeId = "0";
    private List<Shop> shopList;
    private Integer userType;
    private Integer userId;
    private Banner mBanner;//轮播顶部

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        myActivity = (Activity) context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        helper = new MySqliteOpenHelper(myActivity);
        tabTitle = (TabLayout) view.findViewById(R.id.tab_title);
        rvShopList = (RecyclerView) view.findViewById(R.id.rv_list);
        llEmpty = view.findViewById(R.id.ll_empty);
        mBanner = view.findViewById(R.id.banner);
        //获取控件
        initView();
        return view;
    }

    /**
     * 初始化页面
     */
    private void initView() {

        //图片资源
        int[] imageResourceID = new int[]{R.drawable.ic_a, R.drawable.ic_b, R.drawable.ic_c, R.drawable.ic_d};
        List<Integer> imgeList = new ArrayList<>();
        //轮播标题
        for (int i = 0; i < imageResourceID.length; i++) {
            imgeList.add(imageResourceID[i]);//把图片资源循环放入list里面
            //设置图片加载器，通过Glide加载图片
            mBanner.setImageLoader(new ImageLoader() {
                @Override
                public void displayImage(Context context, Object path, ImageView imageView) {
                    Glide.with(myActivity).load(path).into(imageView);
                }
            });
            //设置轮播的动画效果,里面有很多种特效,可以到GitHub上查看文档。
            mBanner.setImages(imgeList);//设置图片资源
            //设置指示器位置（即图片下面的那个小圆点）
            mBanner.setDelayTime(3000);//设置轮播时间3秒切换下一图
            mBanner.start();//开始进行banner渲染,启动轮播图
        }
        /**
         * tab页面 tablayout选项卡
         */
        userType = (Integer) SPUtils.get(myActivity, SPUtils.USER_TYPE, 0);
        userId = (Integer) SPUtils.get(myActivity, SPUtils.USER_ID, 0);
        tabTitle.setTabMode(TabLayout.MODE_SCROLLABLE);
        //为TabLayout添加tab名称
        for (int i = 0; i < title.length; i++) {
            tabTitle.addTab(tabTitle.newTab().setText(title[i]));
        }
        GridLayoutManager layoutManager = new GridLayoutManager(myActivity, 2);//两列
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);//方向，垂直
        //=1.3、设置recyclerView的网格布局管理器GridLayoutManager
        rvShopList.setLayoutManager(layoutManager);
        HashMap<String, Integer> mapSpaces = new HashMap<>();//间距
        mapSpaces.put(RecyclerViewSpaces.TOP_DECORATION, 20);//上间距
        mapSpaces.put(RecyclerViewSpaces.BOTTOM_DECORATION, 20);//下间距
        mapSpaces.put(RecyclerViewSpaces.LEFT_DECORATION, 20);//左间距
        mapSpaces.put(RecyclerViewSpaces.RIGHT_DECORATION, 20);//右间距
        rvShopList.addItemDecoration(new RecyclerViewSpaces(mapSpaces));//设置间距
        mShopAdapter = new ShopAdapter();
        //=2.3、设置recyclerView的适配器
        rvShopList.setAdapter(mShopAdapter);
        loadData();
        mShopAdapter.setItemListener(new ShopAdapter.ItemListener() {
            @Override
            public void ItemClick(Shop shop) {
                if (userId == 0) {//未登录,跳转到登录页面
                    MyApplication.Instance.getMainActivity().finish();
                    startActivity(new Intent(myActivity, LoginActivity.class));
                } else {//已经登录
                    Intent intent;
                    intent = new Intent(myActivity, ShopDetailActivity.class);
                    intent.putExtra("shop", shop);
                    startActivityForResult(intent, 100);
                }
            }

            @Override
            public void Delete(Integer id) {
                AlertDialog.Builder dialog = new AlertDialog.Builder(myActivity);
                dialog.setMessage("确认要删除该商品吗");
                dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SQLiteDatabase db = helper.getWritableDatabase();
                        String sql = "delete from shop where id=?";
                        db.execSQL(sql,new String[]{String.valueOf(id)});
                        db.close();
                        Toast.makeText(myActivity, "删除成功", Toast.LENGTH_SHORT).show();
                        loadData();
                    }
                });
                dialog.setNeutralButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialog.show();
            }
        });
        tabTitle.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                typeId = state[tab.getPosition()];
                loadData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void loadData() {
        shopList = new ArrayList<>();
        Shop shop = null;
        String sql = "select * from shop where typeId ="+typeId;
        SQLiteDatabase db = helper.getWritableDatabase();
        Cursor cursor = db.rawQuery(sql,null);
        if (cursor != null && cursor.getColumnCount() > 0) {
            while (cursor.moveToNext()) {
                Integer dbId = cursor.getInt(0);
                Integer dbTypeId = cursor.getInt(1);
                String dbTitle = cursor.getString(2);
                String dbImg = cursor.getString(3);
                String dbContent = cursor.getString(4);
                String dbPrice = cursor.getString(5);
                String dbDate = cursor.getString(6);
                shop = new Shop(dbId,dbTypeId, dbTitle, dbImg, dbContent, dbPrice,dbDate);
                shopList.add(shop);
            }
        }
        Collections.reverse(shopList);
        if (shopList != null && shopList.size() > 0) {
            rvShopList.setVisibility(View.VISIBLE);
            llEmpty.setVisibility(View.GONE);
            mShopAdapter.addItem(shopList);
        } else {
            rvShopList.setVisibility(View.GONE);
            llEmpty.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        loadData();//加载数据
    }
}
